package tracex

import (
	"time"

	"go.opentelemetry.io/otel/sdk/trace"
)

type SamplerConfig struct {
	SampleRate float64 `json:"sample_rate" toml:"sample_rate" yaml:"sample_rate"`
}
type BatcherConfig struct {
	MaxQueueSize       int  `json:"max_queue_size" toml:"max_queue_size" yaml:"max_queue_size"`
	MaxExportBatchSize int  `json:"max_export_batch_size" toml:"max_export_batch_size" yaml:"max_export_batch_size"`
	BatchTimeout       int  `json:"batch_timeout" toml:"batch_timeout" yaml:"batch_timeout"`
	ExportTimeout      int  `json:"export_timeout" toml:"export_timeout" yaml:"export_timeout"`
	Blocking           bool `json:"blocking" toml:"blocking" yaml:"blocking"`
}

func (c SamplerConfig) NewSampler() trace.Sampler {
	if c.SampleRate <= 0 {
		return trace.NeverSample()
	}

	if c.SampleRate == 1 {
		return trace.AlwaysSample()
	}

	return trace.TraceIDRatioBased(c.SampleRate)
}
func (c SamplerConfig) ProviderOption() trace.TracerProviderOption {
	return trace.WithSampler(c.NewSampler())
}

func (c BatcherConfig) ProviderOption(exporter trace.SpanExporter) trace.TracerProviderOption {
	opts := []trace.BatchSpanProcessorOption{
		trace.WithMaxQueueSize(c.MaxQueueSize),
		trace.WithMaxExportBatchSize(c.MaxExportBatchSize),
		trace.WithBatchTimeout(time.Duration(c.BatchTimeout) * time.Second),
		trace.WithExportTimeout(time.Duration(c.ExportTimeout) * time.Second),
	}
	if c.Blocking {
		opts = append(opts, trace.WithBlocking())
	}

	return trace.WithBatcher(exporter, opts...)
}
